<script setup>
import {defineProps, defineEmits, ref} from 'vue';
import {useRouter} from 'vue-router';
import {showConfirmDialog, showToast} from 'vant';
import api from '@/api/index.js';
import pay from '@/utils/pay.js';

const emit = defineEmits(['onLoad']);
import {useRoute} from 'vue-router';
import {shouldHideBtn} from "@/utils/wx-utils.ts";

const router = useRouter();
const route = useRoute();

const orderType = route.query.title;
const props = defineProps({
  type: [Number, String],
  data: Object,
  types: String,
});

const fileUrl = import.meta.env.VITE_FILE_URL;

///订单状态 0-待支付 1-待使用/待发货 2-待收货 3-已完成 4-退款单 5-已退款 6-订单已取消 11 订单异常

const getTypeText = () => {
  const status = props.data.status;
  if (status === 0) {
    return {
      text: '待支付',
      color: '#ED6316',
    };
  }
  if (status === 1) {
    return {
      text: '待使用',
      color: '#999999',
    };
  }
  if (status === 2) {
    return {
      text: '已完成',
      color: '#999999',
    };
  }
  if (status === 3) {
    return {
      text: '已取消',
      color: '#999999',
    };
  }
  if (status === 4) {
    return {
      text: '退款中',
      color: '#ED6316',
    };
  }
  if (status === 5) {
    return {
      text: '已退款',
      color: '#ED6316',
    };
  }
  if (status === 6) {
    return {
      text: '已取消',
      color: '#999999',
    };
  }
};
const goDetailClick = () => {
  router.push({path: '/activity-order/' + props.data.orderNumber});
};
const refundLoading = ref(false)
const refundClick = () => {
  if (props.data.spuList[0].refundType === '0') {
    showToast('该订单不可退款');
    return;
  }
  refundLoading.value=true
  api
      .getOrderInfo({
        orderNumber: props.data.orderNumber,
      })
      .then((res) => {
        if (res.code === '200') {
          if(res?.data.orderTicketVos.some(e=>e.state===1)){
            showToast('该订单不可以退款')
            return
          }
        }
        router.push({
          path: `/scenic/refund/${props.data.orderNumber}`,
          query: {type: orderType},
        });
      }).finally(()=>{
    refundLoading.value=false

  });

};

const goPayClick = () => {
  // if (orderType === 'scenic') {
  //   pay.getPayld({ orderNumber: props.data.orderNumber, type: 'mini' });
  // } else if (orderType === 'hotel') {
  //   pay.getPayld({ orderNumber: props.data.orderNumber, type: 'hotel' });
  // } else if (orderType === 'hotPot') {
  //   // pay.getPayld({ orderNumber: props.data.orderNumber, type: 'hotel' })
  // }
  pay.getPayld({
    orderNumber: props.data.orderNumber,
    type: 'mini',
    finishUrl: shouldHideBtn() ? null : window.location.origin + '/#' + `activity-order/${props.data.orderNumber}`,
    backUrl:location.href
  });
};

const beforeClose = (action) => {
  return new Promise((resolve) => {
    // if (action === 'confirm') {
    //   if (orderType === 'scenic') {
    //     api
    //       .getcancel({
    //         orderNumber: props.data.orderNumber,
    //       })
    //       .then(() => {
    //         resolve(true);
    //         emit('cancelOrderResetting');
    //       })
    //       .catch(() => {
    //         resolve(false);
    //       });
    //   } else {
    //     // orderType === 'hotel'
    //     api
    //       .getHotelCancelOrder({ orderNumber: props.data.orderNumber })
    //       .then(() => {
    //         resolve(true);
    //         emit('cancelOrderResetting');
    //       })
    //       .catch(() => {
    //         resolve(false);
    //       });
    //   }
    // } else {
    //   resolve(true);
    // }
    if(action!=='confirm'){
      resolve(true);
      return
    }
    api
        .getcancel({
          orderNumber: props.data.orderNumber,
        })
        .then(() => {
          resolve(true);
          emit('cancelOrderResetting');
        })
        .catch(() => {
          resolve(false);
        });
  });
};

const cancelClick = () => {
  showConfirmDialog({
    message: '确定取消该订单?',
    beforeClose,
  });
};
// 再次购买
const handelrepurchase = () => {
  router.push(`/activityAreaDetails/${props.data.shopId}/${props.data.spuList?.[0].reservationType===0? '活动预约':props.data.spuList?.[0].reservationType }`);
};
const goScenicClick = () => {
  if (orderType === 'scenic') {
    router.push(`/scenicspot/${props.data.shopId}`);
  } else if (orderType === 'hotel') {
    router.push(`/hotel-detail/${props.data.shopId}`);
  } else if (orderType === 'hotPot') {
    // router.push(`/scenicspot/${props.data.shopId}`)
  }
};
// console.log('props', JSON.stringify(props.data));

</script>

<template>
  <div class="card">
    <div class="header">
      <div class="header_left" @click="goScenicClick">
        <img src="@/assets/images/icons/shop.jpg" alt=""/>
        <div class="name">{{  data.shopName||data.merchantName  }}</div>
        <van-icon name="arrow" color="#999999"/>
      </div>
      <div class="header_right">
        <img
            v-if="data.status === 0"
            src="@/assets/images/icons/noPay.png"
            alt=""
        />
        <img
            v-else-if="data.status === 1"
            src="@/assets/images/icons/not-used.png"
            alt=""
        />
        <img
            v-else-if="data.status === 2"
            src="@/assets/images/icons/complete.png"
            alt=""
        />
        <img
            v-else-if="data.status === 3 || data.status === 6"
            src="@/assets/images/icons/close.png"
            alt=""
        />
        <img
            v-else-if="data.status === 4"
            src="@/assets/images/icons/refunding.png"
            alt=""
        />
        <img
            v-else-if="data.status === 5"
            src="@/assets/images/icons/refunding2.png"
            alt=""
        />
        <div class="type" :style="{ color: getTypeText().color }">
          {{ getTypeText().text }}
        </div>
      </div>
    </div>
    <div class="content" @click="goDetailClick">
      <div class="content_right">
        <div class="top">
          <div class="name">
            {{ data?.spuList?.[0]?.spuName }}
          </div>
          <div class="price">
            <span class="icon">￥</span>
            <span class="number">{{ data.actualAmount }}</span>
          </div>
        </div>
        <div class="bottom">
          <div class="bottom_item">
           x{{
              data?.spuList?.[0]?.orderSkuVo.buyCount
            }}
          </div>
          <div style="height: 5px"></div>
          <div class="bottom_item"
               v-if="data?.spuList[0]?.scenicSpotTimeSlots && data?.spuList[0]?.scenicSpotTimeSlots[0]">
            {{ data?.spuList[0].reservationType == 0 ? '活动' : '营业' }}时间:{{
              data?.spuList[0]?.scenicSpotTimeSlots[0].timeHour.join('到') + ' ' + data?.spuList[0]?.scenicSpotTimeSlots[0].timeSlot.join(',')
            }}
          </div>
          <div class="bottom_item">
            {{ data?.spuList[0].reservationType == 0 ? '活动' : '门店' }}地址:{{ data?.spuList[0].address }}
          </div>
        </div>
      </div>
      <van-image
          class="van_image"
          lazy-load
          width="8rem"
          height="8rem"
          fit="cover"
          radius="5px"
          :src="`${fileUrl}/${data?.spuList[0].imageId}`"
      >
      </van-image>
    </div>
    <div>
      <div v-if="data?.status === 0" class="button_box">
        <div class="button primary" @click.stop="goPayClick">去支付</div>
        <div class="button default" @click.stop="cancelClick">取消订单</div>
      </div>
      <div v-if="data?.status === 3" class="button_box">
        <div class="button primary" @click="handelrepurchase()">再次购买</div>
      </div>
      <div v-if="data?.status === 1 && data?.spuList?.[0]?.skuTotalPrice" class="button_box">
        <div
            class="button default"
            :class="{ button_disabled: data?.spuList?.[0]?.refundType === '0' }"
            @click.stop="refundClick(data)"
        >
          {{refundLoading? '加载中...': '申请退款'}}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.card {
  background: #fffffc;
  box-shadow: 0 1.2rem 2rem 0 rgba(2, 95, 38, 0.05);
  border-radius: 1rem;
  padding: 1rem 1rem 0 1.5rem;

  .header {
    display: flex;
    justify-content: space-between;

    .header_left {
      display: flex;
      align-items: center;

      .name {
        color: #333333;
        font-weight: bold;
        padding: 0 0.5rem;
      }
    }

    .header_right {
      display: flex;
      align-items: center;

      img {
        width: 1.4rem;
        height: 1.4rem;
      }

      .type {
        margin-left: 0.4rem;
        white-space: nowrap;
      }
    }
  }

  .content {
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
    padding: 1.5rem 0;

    img {
      height: 8rem;
      width: auto;
      border-radius: 0.5rem;
    }

    .content_right {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 1rem;

      .top {
        display: flex;
        justify-content: space-between;

        .name {
          font-size: 1.6rem;
          color: #333333;
          font-weight: bold;
          line-height: 1.9rem;
          word-break: break-all;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .price {
          color: #ed6316;
          margin-left: 1rem;
          font-weight: bold;

          .icon {
            font-size: 1.4rem;
          }

          .number {
            font-size: 1.8rem;
          }
        }
      }

      .bottom {
        color: #999999;
        font-size: 1.2rem;

        .bottom_item {
          line-height: 1.7rem;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .expiring_soon {
          color: #ed6316;
        }
      }
    }
  }

  .button_box {
    display: flex;
    flex-direction: row-reverse;
    padding: 1.5rem 0;
    border-top: 0.1rem solid #eeeeee;

    .button {
      margin-left: 0.5rem;
      height: 3rem;
      line-height: 3rem;
      border-radius: 0.5rem;
      padding: 0 1.5rem;
      font-size: 1.4rem;
    }

    .button_disabled {
      opacity: 0.5;
    }

    .default {
      color: #666666;
      background: rgb(242, 242, 242);
    }

    .default:active {
      color: #666666;
      background: rgb(211, 211, 211);
    }

    .primary {
      color: #ffffff;
      background-color: var(--van-primary-color);
    }

    .primary:active {
      background: #4b947f;
    }
  }
}
</style>
